package com.foreveross.chameleon.task;

import org.apache.http.Header;

import android.content.Context;

import com.foreveross.chameleon.config.ChameleonConfig;
import com.foreveross.chameleon.config.ChameleonConstants;
import com.foreveross.chameleon.listener.AsyncTaskListener;
import com.foreveross.chameleon.utils.PropertiesUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class AppAuthenTask {

	protected Context mContext;
	protected AsyncTaskListener mAppAuthenListener;
	
	public AppAuthenTask(Context context,AsyncTaskListener appAuthenListener) {
		mContext = context;
		mAppAuthenListener = appAuthenListener;
	}
	
	
	public void exec() {
		AsyncHttpClient httpClient = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		String appKey = PropertiesUtil.readProperties(mContext,
				ChameleonConstants.RAW_CONFIG).getString(ChameleonConstants.APP_ID, "");
		String secret = PropertiesUtil.readProperties(mContext,
				ChameleonConstants.RAW_CONFIG).getString(ChameleonConstants.APP_SECRET, "");
		params.add("app_key", appKey);
		params.add("app_secret", secret);
		httpClient.addHeader("User-Agent", "Chameleon");
		httpClient.post(ChameleonConfig.APP_AUTH_URL, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int code, Header[] header, byte[] msg,
							Throwable thrw) {
						// TODO Auto-generated method stub
						if(mAppAuthenListener != null) {
							mAppAuthenListener.onFail(code);
						}
						
					}

					@Override
					public void onSuccess(int code, Header[] header, byte[] msg) {
						// TODO Auto-generated method stub
						String result = new String(msg);
						if(mAppAuthenListener != null) {
							mAppAuthenListener.onSucc(result);
						}
						
					}
			
		});
	}
}
